<?php
/**
 * Created by PhpStorm.
 * User: chen
 * Date: 2016/9/29
 * Time: 17:39
 */
namespace app\home\controller;
use app\common\controller\HomeBase;
use think\Request;
use think\Session;

class Comment extends HomeBase{
    //我的评论
    public function index () {
        $join = [
            ['userinfo u','c.uid=u.uid','LEFT'],
        ];
        $field = [
            'c.*','u.username','u.face','u.face50'
        ];
        $objData = db('Comment')->alias('c')->join($join)->field($field)->where(['c.weibo_uid'=>Session::get('uid')])->paginate(6);
        // 获取分页显示
        $page = $objData->render();
        //组合数据
        $data = [];
        foreach ($objData as $comment) {
            $data[] = [
                'id' => $comment['id'],
                'content' => $comment['content'],
                'time' => $comment['time'],
                'uid' => $comment['uid'],
                'weibo_uid'=> $comment['weibo_uid'],
                'wid' => $comment['wid'],
                'username' => $comment['username'],
                'face' => $comment['face'],
                'face50' => $comment['face50'],
            ];
        }
        $result = [
            'data' => $data,
            'page' => $page,
            'total' => db('Comment')->where(['weibo_uid'=>Session::get('uid')])->count(),
        ];
        return $this->fetch('index',['result'=>$result]);
    }


    /**
     * 获取评论数据
     */
    public function get_comment() {
        $request = Request::instance();
        if ($request->isAjax()) {
            $wid = $request->post('wid');
            $join = [
                ['userinfo u','c.uid=u.uid']
            ];
            $field = [
                'c.*','u.username','u.face50','u.face'
            ];
            $db = db('Comment');
            //统计分页总条数
            $count = $db->where(['wid'=>$wid])->count();
            //总页数
            $total = ceil($count / 4);
            //当前页
            $page = isset($_POST['page']) ? input('page',0,'int') : 1;
            //分页数据
            $limit = $page < 2 ? '0,4' : (4*($page-1)) . ',4';
            $data = $db->alias('c')->join($join)->field($field)->order("c.time desc")->where(['c.wid'=>$wid])->limit($limit)->select();
            if ($data) {
                $str = '';
                foreach ($data as $v) {
                    $str .= '<dl class="comment_content">';
                    $str .= '<dt><a href="' .'/uid/' . $v['uid'] . '">';
                    $str .= '<img src="';
                    if ($v['face']) {
                        $str .= $v['face50'];
                    } else {
                        $str .= '/static/home/images/noface.gif';
                    }
                    $str .= '" alt="' . $v['username'] . '" width="30" height="30"/>';
                    $str .= '</a></dt><dd>';
                    $str .= '<a href="' . '/uid/' . $v['uid'] . '" class="comment_name">';
                    $str .= $v['username'] . '</a> : ' . replace_weibo($v['content']);
                    $str .= '&nbsp;&nbsp;( ' . time_format($v['time']) . ' )';
                    $str .= '<div class="reply">';
                    $str .= '<a href="">回复</a>';
                    $str .= '</div></dd></dl>';
                }
                $url = url('home/comment/get_comment');
                if ($total > 1) {
                    $str .= '<dl class="comment-page">';
                    switch ($page) {
                        case $page > 1 && $page < $total :
                            $str .= '<dd page =" ' .($page - 1). ' " wid = " ' .$wid. '" url=" ' .$url.' ">上一页</dd>';
                            $str .= '<dd page =" ' .($page + 1). ' " wid = " ' .$wid. '" url=" ' .$url.' ">下一页</dd>';
                            break;
                        case $page < $total :
                            $str .= '<dd page =" ' .($page + 1). ' " wid = " ' .$wid. '" url=" ' .$url.' ">下一页</dd>';
                            break;
                        case $page == $total :
                            $str .= '<dd page =" ' .($page - 1). ' " wid = " ' .$wid. '" url=" ' .$url.' ">上一页</dd>';
                            break;
                    }
                    $str .= '</dl>';
                }
                return ['status'=>1,'msg' => $str];
            } else {
                return ['status'=>0];
            }

        }
    }

    /**
     * 提交评论
     */
    public function send_coomment() {
        $request = Request::instance();
        if ($request->isAjax()) {
            $uid = trim(input('post.uid',0,'int'));
            $wid = trim(input('post.wid',0,'int'));
            $isturn = input('post.isturn',0,'int');
            $db = db('Weibo');
            if (!$uid || !$wid) return ['status'=> 0];
            $data = [
                'content' => input('post.content'),
                'time' => time(),
                'weibo_uid' => $uid,
                'wid' => $wid,
                'uid' => session('uid')
            ];
            //获取被评论的用户名
            $username = db('userinfo')->where(['uid'=>$uid])->value('username');

            if (db('Comment')->insert($data)) {
                //处理@用户
                $this->_atmeHandel($data['content'],$wid);
                //处理转发
                if ($isturn) {
                    //如果不是原创微博 重新组合转发内容
                    $field = [
                        'id','content','isturn'
                    ];
                    $weibo = $db->where(['id'=>$wid])->field($field)->find();
                    $content = $weibo['isturn'] ? $data['content'] . ' // @' .$username. ' : ' . $weibo['content'] : $data['content'];
                    $conData = [
                        'content' => $content,
                        'isturn' => $wid,
                        'time' => time(),
                        'uid' => session('uid')
                    ];
                    if ($db->insert($conData)) {
                        //转发数 +1
                        $db->where(['id'=>$wid])->setInc('turn');
                    }
                }
                //评论数+1
                $db->where(['id'=>$wid])->setInc('comment');

                //获取数据
                $field_1 = [
                    'face','username'
                ];
                $user = db('userinfo')->where(['uid'=>$data['uid']])->field($field_1)->find();
                //组合评论样式字符串返回
                $str = '';
                $str .= '<dl class="comment_content">';
                $str .= '<dt><a href="' . '/uid/' . $data['uid'] . '">';
                $str .= '<img src="';
                if ($user['face']) {
                    $str .= $user['face'];
                } else {
                    $str .= '/static/home/images/noface.gif';
                }
                $str .= '" alt="' . $user['username'] . '" width="30" height="30"/>';
                $str .= '</a></dt><dd>';
                $str .= '<a href="' . '/uid/' . $data['uid'] . '" class="comment_name">';
                $str .= $user['username'] . '</a> : ' . replace_weibo($data['content']);
                $str .= '&nbsp;&nbsp;( ' . time_format($data['time']) . ' )';
                $str .= '<div class="reply">';
                $str .= '<a href="">回复</a>';
                $str .= '</div></dd></dl>';

                return ['status'=>1,'msg'=>$str];
            } else {
                return ['status'=>0];
            }
        }
    }

    /**
     * @用户处理
     */
    private function _atmeHandel ($content,$wid) {
        $preg = '/@(\S+?)\s/is';
        preg_match_all($preg,$content,$arr);
        if ($arr[1]) {
            $db = db('Userinfo');
            foreach ($arr[1] as $v) {
                $uid = $db->where(['username' => $v])->value('uid');
                if ($uid) {
                    $data = [
                        'wid' => $wid,
                        'uid' => $uid
                    ];
                    db('Atme')->insert($data);
                }
            }
        }
    }

    /**
     * 转发微博
     */
    public function turn() {
        $request = Request::instance();
        if ($request->isAjax()) {
            //原微博ID
            $id = input('post.id','','int');
            $tid = input('post.tid','','int');
            //转发内容
            $content = input('post.content');
            $data = array(
                'isturn' => $tid ? $tid : $id,
                'content' => $content,
                'time' => time(),
                'uid' => session('uid')
            );
            $db = db('weibo');
            if ($wid = $db->insertGetId($data)) {
                //原微博转发数+1
                $db->where(['id'=>$id])->setInc('turn');
                if ($tid) {
                    //转发的原微博+1
                    $db->where(['id'=>$tid])->setInc('turn');
                }
                //用户微博数+1
                db('userinfo')->where(['uid'=>session('uid')])->setInc('weibo');

                //处理@用户
                $this->_atmeHandel($data['content'],$wid);

                //如果点击了同时评论插入内容到评论表
                if (isset($_POST['becomment'])) {
                    $data = [
                        'content' => $content,
                        'time' => time(),
                        'uid' => session('uid'),
                        'wid' => $id
                    ];
                    //插入数据到评论表后给原微博评论数+1
                    if (db('comment')->insert($data)) {
                        $db->where(array('id' => $id))->setInc('comment');
                    }
                }
                return ['status'=>1,'msg'=>'转发成功.^_^'];
            } else {
                return ['status'=>0,'msg'=>'转发失败请重试...'];
            }
        }
    }
}